package core

import (
	"fmt"
	"log"
	"strconv"

	"github.com/xuri/excelize/v2"
)

// Contains 数组是否包含某元素
func Contains(slice []string, s string) int {
	for index, value := range slice {
		if value == s {
			return index
		}
	}
	return 0
}

//@function: ReadExcel
//@description: 读取Excel
//@param: filePath string, column string
//@return: []string
func ReadExcel(filePath string, isHeader bool) [][]string {
	var result [][]string
	f, err := excelize.OpenFile(filePath)
	if err != nil {
		fmt.Println(err)
		return result
	}
	defer f.Close()
	// 获取 Sheet1 上所有单元格
	rows, err := f.GetRows("Sheet1")
	if err != nil {
		fmt.Println(err)
		return result
	}

	for i, row := range rows {
		if isHeader && i == 0 {
			continue
		}
		result = append(result, row)
	}
	return result
}

func WriteExcel(filePath string, Header []interface{}, data [][]interface{}) {
	// 初始化Excel
	excel := excelize.NewFile()
	// 获取流式写入器
	streamWriter, err := excel.NewStreamWriter("Sheet1")
	if err != nil {
		log.Fatalln("获取流式写入器失败: " + err.Error())
		return
	}
	// 设置对齐方式
	sty_idx, err := excel.NewStyle(&excelize.Style{
		Font: &excelize.Font{
			Bold:   false,
			Size:   11,
			Family: "宋体",
			Color:  "#000000",
		},
		Alignment: &excelize.Alignment{
			Horizontal: "left",
			Vertical:   "left",
		},
	})
	if err != nil {
		log.Fatalln("设置对齐方式失败")
		return
	}
	fmt.Println(sty_idx)
	var index int = 1
	// 写入表头
	if err := streamWriter.SetRow("A"+strconv.Itoa(index), Header); err != nil {
		log.Fatalln("写入表头失败: " + err.Error())
		return
	}
	index += 1

	// 按行写入Excel
	for _, v := range data {
		var rowData []interface{}
		// 遍历每一行数据
		for _, v2 := range v {
			rowData = append(rowData, []interface{}{excelize.Cell{StyleID: sty_idx, Value: v2}}...)
		}

		if err = streamWriter.SetRow("A"+strconv.Itoa(index), rowData); err != nil {
			log.Fatalln("按行写入失败: " + err.Error())
			return
		}

		index += 1
	}

	// 调用 Flush 函数来结束流式写入过程
	if err = streamWriter.Flush(); err != nil {
		log.Fatalln("结束流式写入失败: " + err.Error())
		return
	}
	// 保存表格
	if err := excel.SaveAs(filePath); err != nil {
		log.Fatalln(err)
		return
	}
}
